package com.book.shiro;

import com.book.entity.Role;
import com.book.entity.User;
import com.book.mapper.RoleMapper;
import com.book.mapper.UserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 认证
 *
 * @author wangwei
 * @version 1.0 2018-2-1 10:08:53
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;


        SimpleAuthenticationInfo info = null;
        String name = getName();
        //TODO 登录接口
        String username = token.getUsername();
        String password = new String(token.getPassword());
        User user = userMapper.selectOne(new User(username));
        if (user == null) {
            throw new UnknownAccountException();
        } else {
            if (!user.getPassword().equals(password)) {
                throw new IncorrectCredentialsException();
            } else {
                info = new SimpleAuthenticationInfo(user, password, name);
                ShiroUtils.getSession().setAttribute("currentUser", user);
                ShiroUtils.getSession().setAttribute("currentRole", roleMapper.selectOne(new Role(username)));
            }
        }
        return info;
    }

}
